package old.dbutils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author DingZhenYun
 * @create 2019-03-21 20:33
 */

/**
 * 使用 QueryRunner 提供其具体的实现
 * @param <T>: 子类需传入的泛型类型.
 */
public class JDBCDAOImpl<T> implements DAO<T> {

    private QueryRunner queryRunner = null;
    private Class<T> type;

    public JDBCDAOImpl() {
        queryRunner = new QueryRunner(JDBCTools.getDataSource());
        type = ReflectionUtils.getSuperGenericType(getClass());
    }

    @Override
    public void batch(String sql, Object[]... args) throws SQLException {
        queryRunner.batch(sql, args);
    }

    @Override
    public <E> E getForValue( String sql, Object... args) throws SQLException {
        return (E) queryRunner.query(sql, new ScalarHandler(), args);
    }

    @Override
    public List<T> getForList(String sql, Object... args)
            throws SQLException {
        return queryRunner.query(sql,
                new BeanListHandler<>(type), args);
    }

    @Override
    public T get(String sql, Object... args) throws SQLException {
        return queryRunner.query(sql,
                new BeanHandler<>(type), args);
    }

    @Override
    public void update(String sql, Object... args) throws SQLException {
        queryRunner.update(sql, args);
    }

}
